package com.bootdo.system.shiro;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import com.bootdo.common.config.ApplicationContextRegister;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MenuService;
import com.bootdo.system.service.SuyongService;
import com.bootdo.system.service.UserOldService;

public  class UserRealm extends AuthorizingRealm {
	@Autowired
	UserOldService useroldService;
	@Autowired
	SuyongService suyongService;
	
	

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Long userId = ShiroUtils.getUserId();
		MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
		Set<String> perms = menuService.listPerms(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}
	
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
					String phone= (String) token.getPrincipal();
					String password = new String((char[]) token.getCredentials());
					Map<String, Object> map = new HashMap<>();
					map.put("phone",phone);
					UserDO user=null;
					try {
						user=useroldService.list(map).get(0);
					} catch (Exception e) {
						
					}
					
					// 账号不存在
					if (user == null) {
						throw new UnknownAccountException("账号或密码不正确");
					}
		
					// 密码错误
					if (!password.equals(user.getPassword())) {
						throw new IncorrectCredentialsException("账号或密码不正确");
					}
					// 账号锁定
					if(suyongService.get(user.getId())!=null){
						if (suyongService.get(user.getId()).getStatus() == 0) {
							throw new LockedAccountException("账号已被锁定,请联系管理员");
						}
					}
					
					// 账号逻辑删除
				   if(user.getDelflag() == 1){
					   throw new IncorrectCredentialsException("账号未激活请联系管理员");
					}
					SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
					return info;
		
      
	}
	


}
